package com.znjc.iot.listener;


import cn.hutool.extra.spring.SpringUtil;
import com.znjc.iot.domain.IotSerial;
import com.znjc.iot.serial.SerialPortHandler;
import com.znjc.iot.serial.SerialPortUtil;
import com.znjc.iot.service.IotService;
import com.znjc.iot.util.CommonUtil;
import com.znjc.iot.util.DataUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;

/**
 * @Author:wy
 * @Date: 2023/7/19  14:48
 * @Version 1.0
 */
@Slf4j
public class MyListener extends PortListener {
    IotService iotService;

    public IotService getIotService() {
        if (iotService == null) {
            iotService = SpringUtil.getBean(IotService.class);
        }
        return iotService;
    }

    public MyListener() {
    }

    @Override
    public void onReadException(Exception e) {
        log.error("接收数据异常：{}", e.getMessage());
//        System.out.println("发生异常: " + e.getMessage());
    }


    /**
     * 读取数据
     *
     * @param data
     * @param serialPortVo
     */
    @Override
    public void onReceive(byte[] data, SerialPortUtil serialPortVo, Timestamp date) {
        String needData = DataUtil.printHexString(data);
        log.info(serialPortVo.getName() + "串口接收到数据: " + needData);
        getIotService().analyzeData(needData, date);
    }

    @Override
    public void onBreakInterrupt() {
        new Thread(() -> reconnectSerialPort()).start(); // 异步重连避免阻塞
    }


    private void reconnectSerialPort() {
        IotSerial serialConfig = this.serialPortVo.getIotSerial();
        String portName = serialConfig.getSerialCode();
        while (true) {
            try {
                log.info("尝试重连串口: {}", portName);
                // 1. 清理旧资源
                serialPortVo.closePort();
                CommonUtil.protUtils.remove(portName);
                CommonUtil.openComs.remove(portName);

                // 2. 尝试重新打开
                SerialPortUtil newPort = SerialPortHandler.openSerialPort(serialConfig);
                if (newPort != null) {
                    log.info("串口 {} 重连成功", portName);
                    return;
                }
            } catch (Exception e) {
                log.error("重连失败: {}", e.getMessage());
            }

            // 3. 等待后重试
            try {
                Thread.sleep(5000); // 5秒后重试
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
    /* *//**
     * 发送数据
     *
     * @param serialPortVo
     * @param hex          发送数据
     *//*
    public void sendData(SerialPortUtil serialPortVo, String hex) throws SendDataToSerialPortFailure, SerialPortOutputStreamCloseFailure {
        log.info("发送数据开始 .......");
        byte[] sendMsg = CRC16M.getSendBuf(hex);
        serialPortVo.sendData(sendMsg);
        log.info("发送数据结束 .......");
    }*/
}
